package routers

import (
	"adminHome/middleware/jwt"
	"adminHome/pkg/setting"
	"adminHome/pkg/upload"
	"adminHome/routers/api"
	v1 "adminHome/routers/api/v1"
	"github.com/gin-gonic/gin"
	"net/http"
)

func InitRouter() *gin.Engine {
	r := gin.New()

	r.Use(gin.Logger())

	r.Use(gin.Recovery())

	r.Use(cors())

	gin.SetMode(setting.ServerSetting.RunMode)

	r.StaticFS("/upload/images", http.Dir(upload.GetImageFullPath()))
	r.GET("api/v1/login", api.GetAuth)
	r.POST("api/v1/upload", api.UploadImage)

	apiv1 := r.Group("api/v1")
	apiv1.Use(jwt.JWT())
	{
		apiv1.GET("storage", v1.GetStorage)
		apiv1.GET("storage/get", v1.GetStorageById)
		apiv1.POST("storage/add", v1.AddStorage)
		apiv1.POST("storage/edit", v1.EditStorage)
		apiv1.POST("storage/del", v1.DeleteStorage)

		apiv1.GET("product", v1.GetProduct)
		apiv1.GET("product/list", v1.GetProductList)
		apiv1.POST("product/add", v1.AddProduct)
		apiv1.POST("product/edit", v1.EditProduct)
		apiv1.POST("product/del", v1.DelProduct)

		apiv1.GET("user/list", v1.GetUserList)
		apiv1.POST("user/add", v1.AddUser)
		apiv1.POST("user/edit", v1.EditUser)
		apiv1.GET("user/get", v1.GetUser)
		apiv1.POST("user/del", v1.DeleteUser)

		apiv1.POST("inorder/add", v1.AddInOrder)
		apiv1.POST("inorder/edit", v1.EditInOrder)
		apiv1.GET("inorder/get", v1.GetInOrder)
		apiv1.GET("inorder/list", v1.GetInOrderList)
		apiv1.GET("inorder/del", v1.DeleteInOrder)

		apiv1.POST("outorder/add", v1.AddOutOrder)
		apiv1.POST("outorder/edit", v1.EditOutOrder)
		apiv1.GET("outorder/get", v1.GetOutOrder)
		apiv1.GET("outorder/list", v1.GetOutOrderList)
		apiv1.GET("outorder/del", v1.DeleteOutOrder)

		apiv1.GET("stock/get", v1.GetStock)
		apiv1.GET("stock/list", v1.GetStockList)
		apiv1.POST("stock/add", v1.AddStock)
		apiv1.POST("stock/edit", v1.EditStockNum)

	}

	return r
}

func cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		origin := c.Request.Header.Get("origin")
		if len(origin) == 0 {
			origin = c.Request.Header.Get("Origin")
		}
		c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "OPTIONS, GET, POST")
		c.Writer.Header().Set("Content-Type", "application/json; charset=utf-8")
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}
		c.Next()
	}
}
